//  Created by zmyl on 2025/6/10.
//  Copyright © 2025 zmyl. All rights reserved.

#import "MBProgressHUD+Count.h"
#import <libkern/OSAtomic.h>
#import <stdatomic.h>

static atomic_int _activityCount = 0; // 使用 atomic_int 替代 int32_t

@implementation MBProgressHUD (Count)

+ (void)incrementActivityCount {
    dispatch_async(dispatch_get_main_queue(), ^{
        // 使用原子操作替代 OSAtomicIncrement32
        atomic_fetch_add_explicit(&_activityCount, 1, memory_order_relaxed);

        /// 检查是否需要显示 HUD
        if (atomic_load_explicit(&_activityCount, memory_order_relaxed) == 1) {
            UIWindow *targetWindow = [self findBestWindow];
            [MBProgressHUD showHUDAddedTo: targetWindow animated:YES];
        }
    });
}

+ (void)decrementActivityCount {
    dispatch_async(dispatch_get_main_queue(), ^{
        // 获取减少前的值用于日志
        int preCount = atomic_load_explicit(&_activityCount, memory_order_relaxed);
        // 使用原子操作减少计数
        atomic_fetch_sub_explicit(&_activityCount, 1, memory_order_relaxed);

        // 获取减少后的值
        int newCount = atomic_load_explicit(&_activityCount, memory_order_relaxed);
        NSLog(@"MBProgressHUD计数器减少: %d -> %d", preCount, newCount);

        // 处理计数器归零
        if (newCount <= 0) {
            atomic_store_explicit(&_activityCount, 0, memory_order_relaxed);
            UIWindow *targetWindow = [self findBestWindow];
            [MBProgressHUD hideHUDForView:targetWindow animated:YES];

            //            // 确保只隐藏一次
            //            static BOOL hasHidden = NO;
            //            if (!hasHidden) {
            //                [MBProgressHUD hideHUDForView:targetWindow animated:YES];
            //                hasHidden = YES;
            //                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            //                    hasHidden = NO;
            //                });
            //            }
        }
    });
}

// 找到最适合显示HUD的窗口(四级回退策略确保总能找到合适的窗口)
+ (UIWindow *)findBestWindow {
    // 1. 优先使用应用委托指定的窗口
    if ([TPAPPDelegate respondsToSelector:@selector(mainWindow)]) {
        UIWindow *mainWindow = [TPAPPDelegate mainWindow];
        if (mainWindow) return mainWindow;
    }

    // 2. 使用keyWindow
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    if (keyWindow) return keyWindow;

    // 3. 使用最顶层的窗口
    NSArray *windows = [UIApplication sharedApplication].windows;
    for (UIWindow *window in windows.reverseObjectEnumerator) {
        if (window.windowLevel == UIWindowLevelNormal && !window.hidden) {
            return window;
        }
    }

    // 4. 最后尝试主窗口
    return [UIApplication sharedApplication].delegate.window;
}
@end
